﻿using System;
using Epm.AppLogic.Framework;
using msBsc.Xsd.DataTds;
using System.Data;
using System.Text;

namespace msBsc.AppLogic.DataAlc
{
    /// <summary>
    /// 地接客发布帖子的原帖信息
    /// </summary>
    public class CBizSourcePosts : CustBizObject
    {
        private CDmDjkSourcePosts m_CDmDjkSourcePosts = new CDmDjkSourcePosts();
        private CDmDjkSourcePosts oDmDjkSourcePosts
        {
            get { return m_CDmDjkSourcePosts; }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public CBizSourcePosts()
            : base()
        {
            this.DataObj = new CDbAccess();
            this.DataObj.Init(this.m_CDmDjkSourcePosts.DJK_SOURCE_POSTS);
            this.TableName = this.DataObj.TableName;
            this.DataObj.KeyField = this.DataObj.Fields["SOURCE_POSTS_ID"];
        }

        /// <summary>
        /// 新增记录前的处理
        /// </summary>
        /// <param name="drw">新增数据行</param>
        /// <returns>true/false</returns>
        /// <remarks>
        /// 生成ID值
        /// </remarks>
        protected override bool BeforeRowAdded(DataRow drw)
        {
            if (drw[this.KeyFieldName].ToString().Length < 10)
            {
                drw[this.KeyFieldName] = this.DataObj.NewID();
            }

            return true;
        }

        /// <summary>
        /// 记录修改前检验
        /// </summary>
        /// <param name="drw">当前记录</param>
        /// <returns>>校验合法，返回值为true,否则返回false</returns>
        /// <remarks>
        /// ID不允许修改,并把此修改操作记录到BSE_MODIFY_HISTORY表中
        /// </remarks>
        protected override bool BeforeRowModified(DataRow drw)
        {
            //ID不容许修改
            if (drw[this.KeyFieldName].ToString() != drw[this.KeyFieldName, DataRowVersion.Original].ToString())
            {
                Exception e = new Exception(this.TableName + "表的主键" + this.KeyFieldName + "字段不允许被修改");
                throw e;
            }
            return true;
        }
        protected override bool BeforeRowDeletedR(DataRow drw)
        {
            //using (msBsc.AppLogic.DataAlc.CBizShpPageColumn objtem = new CBizShpPageColumn())
            //{
            //    DataSet ds = objtem.SelectByPageNo(this.GetRowStr(drw, KeyFieldName));
            //    for (int i = ds.Tables[0].Rows.Count - 1; i >= 0; i--)
            //    {
            //        ds.Tables[0].Rows[i].Delete();
            //    }
            //    objtem.Update(ds);
            //} 
            return true;
        }

        protected override bool AfterRowAdded(DataRow drw)
        {
            return true;
        }

        protected override bool AfterRowModified(DataRow drw)
        {
            return true;
        }

        protected override bool AfterRowDeletedR(DataRow drw)
        {
            return true;
        }

        /// <summary>
        /// 修改原帖信息
        /// </summary>
        /// <param name="recoverId">帖子ID</param>
        /// <param name="recoverBy">回复人</param>
        public void UpdateSourcePosts(string recoverId, string recoverBy)
        {
            DataSet ds = GetPostsByRecoverId(recoverId);
            DataRow dr = ds.Tables[0].Rows[0];
            dr["POSTS_RECOVER_COUNT"] = SelectRecoverCountById(recoverId) + 1;
            dr["POSTS_HAS_NEW_RECD"] = true;
            dr["POSTS_LAST_RECOVER"] = recoverBy;
            //ds.Tables[0].Rows.Add(dr);
            this.Update(ds);
        }

        /// <summary>
        /// 新增论坛
        /// </summary>
        /// <param name="publishId">发布者ID</param>
        /// <param name="postsTitle">论坛标题</param>
        /// <param name="postsContent">论坛内容</param>
        /// <returns></returns>
        public string[] AddSourcePosts(string publishId, string postsTitle, string postsContent, string countryId, string cityId, string destId, string keywords, int postsStatus = 1)
        {
            #region 验证输入是否合法
            if (string.IsNullOrEmpty(publishId))
            {
                return new string[] { "FALSE", "发帖人不能为空" };
            }
            if (string.IsNullOrEmpty(postsTitle))
            {
                return new string[] { "FALSE", "帖子标题不能为空" };
            }
            if (string.IsNullOrEmpty(countryId) || string.IsNullOrEmpty(cityId))
            {
                return new string[] { "FALSE", "请至少选择两级地区信息" };
            }
            if (string.IsNullOrEmpty(keywords))
            {
                return new string[] { "FALSE", "请输入关键字，让你的推荐更易被查找" };
            }
            if (keywords.Length > 125)
            {
                return new string[] { "FALSE", "关键字过长，不能超过120个字符" };
            }
            if (postsTitle.Length > 100)
            {
                return new string[] { "FALSE", "帖子标题不能超过100字符" };
            }
            if (string.IsNullOrEmpty(postsContent))
            {
                return new string[] { "FALSE", "帖子内容不能为空" };
            }
            #endregion

            DataSet ds = new CDmDjkSourcePosts();
            DataRow dr = ds.Tables[0].NewRow();
            dr["SOURCE_POSTS_ID"] = this.DataObj.NewID();
            dr["POSTS_PUBLISH_BY"] = publishId;
            dr["SOURCE_POSTS_TITLE"] = postsTitle;
            dr["POSTS_CONTENT"] = string.Empty;
            dr["POSTS_IS_REVIEW"] = 0;
            dr["POSTS_IS_BOUTIQUE"] = 0;
            dr["POSTS_RECOVER_COUNT"] = 0;
            dr["POSTS_PUBLISH_TIME"] = this.dtCurrDateTime;
            dr["POSTS_HAS_NEW_RECD"] = 0;
            dr["POSTS_IS_SELF_PBH"] = 0;
            dr["POSTS_CLICK_COUNT"] = 0;
            dr["POSTS_LAST_RECOVER"] = null;
            dr["POSTS_LAST_CLICK"] = null;
            dr["POSTS_IS_DELETED"] = 0;
            dr["POSTS_IS_DISPLAY"] = 1;
            dr["POSTS_RMK"] = null;
            dr["POSTS_STATUS"] = postsStatus;
            dr["POSTS_COUNTRY"] = countryId;
            dr["POSTS_CITY"] = cityId;
            dr["POSTS_DESTINATION"] = destId;
            dr["POSTS_KEYWORDS"] = keywords;

            string strVpath = msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strSaveUploadSysFileDirV + this.DataObj.NewID() + ".html";//存储文件的虚拟路径
            if (postsContent != string.Empty && strVpath != string.Empty)
            {
                string strFFullPath = System.Web.HttpContext.Current.Server.MapPath(strVpath);
                using (System.IO.TextWriter streamWriter = new System.IO.StreamWriter(strFFullPath))
                {
                    streamWriter.Write(postsContent);
                }
                dr["CONTENT_HTML_URL"] = strVpath;
                //System.IO.File.WriteAllText(strFFullPath, strHeadHtml, System.Text.Encoding.UTF8);
            }



            ds.Tables[0].Rows.Add(dr);
            this.Update(ds);
            return new string[] { "OK", "发布成功" };
        }

        #region 论坛列表分页查询
        /// <summary>
        /// 查询论坛 分页
        /// </summary>
        /// <param name="pageRows">每页多少条记录</param>
        /// <param name="pageNum">第几页</param>
        /// <param name="djkId">地接客ID</param>
        /// <returns></returns>
        public DataSet GetVehicleForPageview(int pageRows, int pageNum, string djkId, string destination = "", string cityid = "", string countryid = "", string postsKey = "")
        {
            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("ipagerows", ParameterDirection.Input, EDbType.String, 36, pageRows));
            parmCollection.Add(new CDbParm("ipagenum", ParameterDirection.Input, EDbType.String, 36, pageNum));
            parmCollection.Add(new CDbParm("djkid", ParameterDirection.Input, EDbType.String, 36, djkId));
            parmCollection.Add(new CDbParm("destination", ParameterDirection.Input, EDbType.String, 36, destination));
            parmCollection.Add(new CDbParm("cityid", ParameterDirection.Input, EDbType.String, 36, cityid));
            parmCollection.Add(new CDbParm("countryid", ParameterDirection.Input, EDbType.String, 36, countryid));
            parmCollection.Add(new CDbParm("postsKey", ParameterDirection.Input, EDbType.String, 36, postsKey));
            DataSet ds = this.DataObj.QueryBySP("DJK_SELECT_POSTS_FOR_VIEW", parmCollection);
            return ds;
        }
        /// <summary>
        /// 根据论坛ID查询所有的回复分页
        /// </summary>
        /// <param name="pageRows">每页多少条记录</param>
        /// <param name="pageNum">第几页</param>
        /// <param name="postid">论坛ID</param>
        /// <returns></returns>
        public DataSet GetRevocerForPageview(int pageRows, int pageNum, string postid)
        {
            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("ipagerows", ParameterDirection.Input, EDbType.String, 36, pageRows));
            parmCollection.Add(new CDbParm("ipagenum", ParameterDirection.Input, EDbType.String, 36, pageNum));
            parmCollection.Add(new CDbParm("postid", ParameterDirection.Input, EDbType.String, 36, postid));
            DataSet ds = this.DataObj.QueryBySP("DJK_SELECT_RECOVER_FOR_VIEW", parmCollection);
            return ds;
        }
        #endregion

        /// <summary>
        /// 查询论坛详情
        /// </summary>
        /// <param name="postsId">论坛ID</param>
        /// <returns>SOURCE_POSTS_TITLE：论坛标题，POSTS_CONTENT：论坛内容，POSTS_PUBLISH_TIME：发布时间，CUSTOMER_NICK：地接客昵称，CUSTOMER_DEFAULT_PIC：头像</returns>
        public DataSet GetPostsForView(string postsId)
        {
            if (string.IsNullOrEmpty(postsId))
            {
                return null;
            }
            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("POSTSID", ParameterDirection.Input, EDbType.String, 36, postsId.Replace("'", "").Replace(",", "','")));
            DataSet ds = this.DataObj.QueryBySQL(@"SELECT T.* ,B.CUSTOMER_NICK,B.CUSTOMER_DEFAULT_PIC FROM
    (SELECT A.SOURCE_POSTS_ID,A.SOURCE_POSTS_TITLE,A.POSTS_PUBLISH_BY,A.POSTS_CONTENT,
    A.POSTS_RECOVER_COUNT,A.POSTS_LAST_RECOVER,A.POSTS_PUBLISH_TIME,A.POSTS_CLICK_COUNT,A.CONTENT_HTML_URL
    FROM DJK_SOURCE_POSTS A
    WHERE A.POSTS_IS_DELETED=0 AND A.POSTS_IS_DISPLAY=1 AND A.SOURCE_POSTS_ID=@POSTSID) T
    LEFT JOIN DJK_CUSTOMER_REGISTER B
    ON T.POSTS_PUBLISH_BY=B.CUSTOMER_REGISTER_ID", parmCollection);
            return ds;
        }


        /// <summary>
        /// 根据帖子ID查询帖子信息
        /// </summary>
        /// <param name="postId">原帖ID</param>
        /// <returns></returns>
        public DataSet GetPostsByRecoverId(string postId)
        {
            if (string.IsNullOrEmpty(postId))
            {
                return null;
            }

            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("POSTID", ParameterDirection.Input, EDbType.String, 36, postId.Replace("'", "").Replace(",", "','")));
            DataSet ds = this.DataObj.QueryBySQL(@"SELECT * FROM DJK_SOURCE_POSTS WHERE SOURCE_POSTS_ID=@POSTID", parmCollection);
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }

        /// <summary>
        /// 根据帖子编号查询当前帖子回复总数
        /// </summary>
        /// <param name="postsId">帖子编号</param>
        /// <returns>帖子回复总数</returns>
        private int SelectRecoverCountById(string postsId)
        {
            if (string.IsNullOrEmpty(postsId))
            {
                return -1;
            }
            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("POSTSID", ParameterDirection.Input, EDbType.String, 36, postsId.Replace("'", "").Replace(",", "','")));
            DataRow dr = this.DataObj.QueryBySQL("SELECT POSTS_RECOVER_COUNT FROM DJK_SOURCE_POSTS WHERE SOURCE_POSTS_ID=@POSTSID", parmCollection).Tables[0].Rows[0];

            return dr["POSTS_RECOVER_COUNT"] is DBNull ? 0 : Convert.ToInt32(dr["POSTS_RECOVER_COUNT"]);
        }


        public DataSet GetPostsInfoBySP(string postsStatus, string postsKey, bool isDel, bool isDis)
        {
            CDbParmCollection parmCollection = new CDbParmCollection();

            parmCollection.Add(new CDbParm("postsstatus", ParameterDirection.Input, EDbType.Integer, 1, postsStatus));
            parmCollection.Add(new CDbParm("postskey", ParameterDirection.Input, EDbType.String, 100, postsKey.Replace("'", "").Replace(",", "','")));
            parmCollection.Add(new CDbParm("isdel", ParameterDirection.Input, EDbType.Boolean, 1, isDel));
            parmCollection.Add(new CDbParm("isdis", ParameterDirection.Input, EDbType.Boolean, 1, isDis));

            return this.DataObj.QueryBySP("DJK_SELECT_POSTS_FOR_VALID", parmCollection);
        }

        public DataSet GetAllPosts()
        {
            DataSet ds = this.DataObj.QueryBySQL(@"SELECT * FROM DJK_SOURCE_POSTS");
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }

    }
}
